#include "Server.h"
#include "FUNCTIONS.h"
#include <boost/asio.hpp>

#ifdef _WIN32 // Check if compiling for Windows
#include <winsock2.h>
#define close_socket(s) closesocket(s)
#else // Assume POSIX-compliant system (e.g., Linux)
#include <unistd.h>
#include <sys/socket.h>
#include <netinet/in.h>
#define close_socket(s) close(s)
#endif

using namespace boost::asio;
using ip::tcp;

void Server::handleClient(tcp::socket& socket) {
    boost::system::error_code error;

    // 读取请求数据
    boost::asio::streambuf buffer;
    boost::asio::streambuf::mutable_buffers_type bufs = buffer.prepare(1024);
    size_t n = socket.read_some(bufs);
    buffer.commit(n);

    if (!error) {
            //  解析请求 把请求存在字符串request中
        boost::asio::streambuf::const_buffers_type data = buffer.data();
        std::string request(boost::asio::buffer_cast<const char*>(data), boost::asio::buffer_size(data));
        

        // 解析请求中的JSON数据
        //std::cout << "request:" << request << std::endl;
        std::string jsonRequest = Functions::extractJsonData(request);
        Json::CharReaderBuilder reader;
        Json::Value jsonData;
        std::istringstream jsonStream(jsonRequest);
        Json::parseFromStream(reader, jsonStream, &jsonData, nullptr);

        //分离路由标识和多维标识

        std::string ifn = "";
        std::string rid = "";
        Json::Value mid = jsonData["multi_id"];
        std::string mac = jsonData["mac"].asString();
        std::string data_id = jsonData["data_id"].asString();

        //通过socket寻找对应ifn
        struct ifaddrs* ifaddr;
        struct ifaddrs* ifa;
        getifaddrs(&ifaddr);
        tcp::endpoint localEndpoint = socket.local_endpoint();
        for (ifa = ifaddr; ifa != NULL; ifa = ifa->ifa_next)
        {

            if (ifa->ifa_addr)
            {

                if (AF_INET == ifa->ifa_addr->sa_family)
                {

                    struct sockaddr_in* inaddr = (struct sockaddr_in*)ifa->ifa_addr;
                    boost::asio::ip::address ifAddr = boost::asio::ip::address::from_string(inet_ntoa(inaddr->sin_addr));
                    if (ifAddr == localEndpoint.address())
                    {

                        if (ifa->ifa_name)
                        {
                            // Found it
                            ifn = ifa->ifa_name;

                            break;
                        }
                    }
                }
            }
        }

        for (ifa = ifaddr; ifa != NULL; ifa = ifa->ifa_next)
        {

            if (ifa->ifa_name && ifa->ifa_addr && ifa->ifa_addr->sa_family == AF_INET6){
                
                if (ifn == ifa->ifa_name){
                    
                    char ipv6AddressStr[INET6_ADDRSTRLEN];
                    Functions::ipv6_to_str_unexpanded(ipv6AddressStr, &((struct sockaddr_in6*)ifa->ifa_addr)->sin6_addr);
                    rid = ipv6AddressStr;
                    
                    if("fe80" != rid.substr(0, 4))
                        
                        break;

                }
            }
        }
        std::cout << "ifn为:" << ifn << std::endl;
        std::cout << "rid为:" << rid << std::endl;
        freeifaddrs(ifaddr);
        //认证部分先不做
        // if(!mid.isMember("user_id") || mid["user_id"].asString() == ""){
        //     //直接结束
        // Json::Value err_code;
        // err_code["err_no"] = 3;
        // std::string json_errcd = err_code.toStyledString();
        
        // std::string httpErrorResponse = "HTTP/1.1 403 Method Not Allowed\r\n"
        //     "Content-Length: " + std::to_string(json_errcd.size()) + "\r\n"
        //     "Content-Type: application/json\r\n"  
        //     "\r\n"  
        //     + json_errcd;
        // boost::asio::write(socket, boost::asio::buffer(httpErrorResponse));
        //     return;
        // }
        // //向认证服务器查询该终端是否通过认证
        // Json::Value user_json;
        // user_json["user_id"] = mid["user_id"];
        // Json::Value id_res = Functions::send_post_request(RENZHENG_IP, user_json.toStyledString());
        // if(!id_res.isMember("flag") || !id_res["flag"].asBool()){
        //     //认证不通过，直接结束
        //     Json::Value err_code;
        //     err_code["err_no"] = 4;
        //     std::string json_errcd = err_code.toStyledString();
            
        //     std::string httpErrorResponse = "HTTP/1.1 403 Forbidden\r\n"
        //         "Content-Length: " + std::to_string(json_errcd.size()) + "\r\n"
        //         "Content-Type: application/json\r\n"  
        //         "\r\n"  
        //         + json_errcd;
        //     boost::asio::write(socket, boost::asio::buffer(httpErrorResponse));
        //     return;
        // }
        
        // 多维标识json数据转string
        std::string jsonData_str = Functions::jsonToString(mid);

        // MD5哈希生成cid
        std::string md5_cid;
        if(data_id == "0"){
            //test
            std::cout << "收到注册的多维标识：" <<jsonData_str << std::endl;
            md5_cid = Functions::calculateMD5Hash(jsonData_str);
        }else{
            
            md5_cid = Functions::calculateMD5Hash(data_id);
        }

        //测试用
        std::cout << md5_cid << std::endl;

        //  存入数据库
        std::cout << "注册：调用函数存入数据库" << std::endl;
        Functions::URLEncode(jsonData_str);      //先把多维标识转换为url格式字符串
        std::string url = SERVER_IP + "/store?cid=" + md5_cid + "&multi_id=" + jsonData_str + "&route_id=" + rid + "&mac_id=" + mac + "&ifn=" + ifn;
        Json::Value State = Functions::send_get_request(url);
        
        //判断存库成功后继续进行后续操作
        if(State.isMember("state") && State["state"].asString() == "ok"){
            //向关联验证发送消息
            Json::Value Anc_Json = mid;
            Anc_Json["cid"] = md5_cid;
            if(GUANLIAN_IP != "0"){ //控制是否向关联验证服务器发包
                Functions::send_post_request(GUANLIAN_IP, Anc_Json.toStyledString());
            }
            // std::thread th(Functions::send_post_request, GUANLIAN_IP, Anc_Json.toStyledString());
            // th.detach();

            //组建http response消息
            Json::Value jsonstr;
            jsonstr["cid"] = md5_cid;
            jsonstr["err_no"] = 0;
            std::string json_cid = "{\"cid\":\"" + md5_cid + "\",\"err_no\":\"0\"}";
            
            std::string httpResponse = "HTTP/1.1 200 OK\r\n"
                "Content-Length: " + std::to_string(json_cid.size()) + "\r\n"
                "Content-Type: application/json\r\n"  
                "\r\n"  
                + json_cid;
            boost::asio::write(socket, boost::asio::buffer(httpResponse));

            //测试用
            std::cout << "注册：已回复终端" << std::endl;
        }else{
            Json::Value err_code;
            err_code["err_no"] = 500;
            std::string json_errcd = "{\"cid\":\"\",\"err_no\":\"500\"}";
            
            std::string httpErrorResponse = "HTTP/1.1 500 Internal Server Error\r\n"
                "Content-Length: " + std::to_string(json_errcd.size()) + "\r\n"
                "Content-Type: application/json\r\n"  
                "\r\n"  
                + json_errcd;
            boost::asio::write(socket, boost::asio::buffer(httpErrorResponse));
        }
    }
    
    else{
        Json::Value err_code;
            err_code["err_no"] = 400;
            std::string json_errcd = "{\"cid\":\"\",\"err_no\":\"400\"}";
            
            std::string httpErrorResponse = "HTTP/1.1 400 Bad Request\r\n"
                "Content-Length: " + std::to_string(json_errcd.size()) + "\r\n"
                "Content-Type: application/json\r\n"  
                "\r\n"  
                + json_errcd;
            boost::asio::write(socket, boost::asio::buffer(httpErrorResponse));
    }
}
//******************************************************************************************************************************************************************************
void Server::ListenAndStore()
{
    io_context io_context;
    tcp::endpoint endpoint(tcp::v4(), 9090);
    tcp::acceptor acceptor(io_context, endpoint);

    //测试用
    std::cout << "进入ListenAndStore函数" << std::endl;
    
    while (true) {
        tcp::socket socket(io_context);
        acceptor.accept(socket);

        //测试用
        std::cout << "ListenAndStore中:socket连接完成,准备调用新线程处理" << std::endl;

        // 在新线程中处理连接
        
        Server::handleClient(socket); 
        std::cout << "ListenAndStore中:退出了注册函数" << std::endl;
        socket.close();
        std::cout << "ListenAndStore中:本次socket连接关闭" << std::endl;
    }
}

//******************************************************************************************************************************************************************************
void Server::Delete()
{
    io_context io_context;
    tcp::endpoint endpoint(tcp::v4(), 9091);
    tcp::acceptor acceptor(io_context, endpoint);

    
    
    while (true) {
        tcp::socket socket(io_context);
        acceptor.accept(socket);

        
        boost::system::error_code error;

        // 读取请求数据
        boost::asio::streambuf buffer;
        boost::asio::streambuf::mutable_buffers_type bufs = buffer.prepare(1024);
        size_t n = socket.read_some(bufs);
        buffer.commit(n);

        if (!error) {
                //  解析请求 把请求存在字符串request中
            boost::asio::streambuf::const_buffers_type data = buffer.data();
            std::string request(boost::asio::buffer_cast<const char*>(data), boost::asio::buffer_size(data));
            

            // 解析请求中的JSON数据
            //std::cout << "request:" << request << std::endl;
            std::string jsonRequest = Functions::extractJsonData(request);
            Json::CharReaderBuilder reader;
            Json::Value jsonData;
            std::istringstream jsonStream(jsonRequest);
            Json::parseFromStream(reader, jsonStream, &jsonData, nullptr);

            //test
            std::cout << "标识app:准备删除通信标识：" << jsonData << std::endl;
            Json::Value res = Functions::send_get_request(SERVER_IP + "/delete_cid?cid=" + jsonData["cid"].asString());
            
            if(res.isMember("state") && res["state"].asString() == "ok"){ //这里返回的是errno=“0”不是state改一下
                //组建http response消息
                Json::Value jsonstr;
                std::string json_res = "{\"err_no\":\"0\"}";
                
                std::string httpResponse = "HTTP/1.1 200 OK\r\n"
                    "Content-Length: " + std::to_string(json_res.size()) + "\r\n"
                    "Content-Type: application/json\r\n"  
                    "\r\n"  
                    + json_res;
                boost::asio::write(socket, boost::asio::buffer(httpResponse));
                std::cout << "标识app:cid删除成功" << std::endl;

            
            }else{
                std::string json_errcd = "{\"err_no\":\"500\"}";
                
                std::string httpErrorResponse = "HTTP/1.1 500 Internal Server Error\r\n"
                    "Content-Length: " + std::to_string(json_errcd.size()) + "\r\n"
                    "Content-Type: application/json\r\n"  
                    "\r\n"  
                    + json_errcd;
                boost::asio::write(socket, boost::asio::buffer(httpErrorResponse));
                std::cout << "标识app:cid删除未成功" << std::endl;
            }
            
            
        }
        socket.close();
    }
}

//******************************************************************************************************************************************************************************
void Server::Connect()
{
    io_context io_context;
    tcp::endpoint endpoint(tcp::v4(), 40001);
    tcp::acceptor acceptor(io_context, endpoint);
    Json::Value err_code;


    redisContext *c;
    c = redisConnect("127.0.0.1", 6379);
    if (c == NULL || c->err) {
        if (c) {
            printf("Connection error: %s\n", c->errstr);
            redisFree(c);
        } else {
            printf("Connection error: can't allocate redis context\n");
        }
        // 处理连接错误
    }
    
    while (true) {
        tcp::socket socket(io_context);
        acceptor.accept(socket);

        //测试用
        std::cout << "Connect:收到终端接线请求" << std::endl;

        boost::system::error_code error;

        // 读取请求数据
        boost::asio::streambuf buffer;
        boost::asio::streambuf::mutable_buffers_type bufs = buffer.prepare(1024);
        size_t n = socket.read_some(bufs);
        buffer.commit(n);

        if (!error) {
                //  解析请求 把请求存在字符串request中
            boost::asio::streambuf::const_buffers_type data = buffer.data();
            std::string request(boost::asio::buffer_cast<const char*>(data), boost::asio::buffer_size(data));

            // 解析请求中的JSON数据
            std::string jsonRequest = Functions::extractJsonData(request);
            Json::CharReaderBuilder reader;
            Json::Value jsonData;
            std::istringstream jsonStream(jsonRequest);
            Json::parseFromStream(reader, jsonStream, &jsonData, nullptr);

            std::string scid = jsonData["scid"].asString();
            std::string dcid = jsonData["dcid"].asString();
            int         flag = 0;
            Json::Value result1 = Functions::processCidAndGetRid(scid);     //获取scid对应表项
            flag = result1["err_no"].asInt();
            if(flag){
                err_code["err_no"] = 404;
                std::string json_errcd = "{\"err_no\":\"404\"}";
                std::string httpErrorResponse = "HTTP/1.1 404 Not Found\r\n"
                    "Content-Length: " + std::to_string(json_errcd.size()) + "\r\n"
                    "Content-Type: application/json\r\n"  
                    "\r\n"  
                    + json_errcd;
                boost::asio::write(socket, boost::asio::buffer(httpErrorResponse));
                socket.close();
                continue;
            } 

            Json::Value result2 = Functions::processCidAndGetRid(dcid);     //获取dcid对应表项
            flag = result2["err_no"].asInt();
            if(flag){
                err_code["err_no"] = 404;
                std::string json_errcd = "{\"err_no\":\"404\"}";
                std::string httpErrorResponse = "HTTP/1.1 404 Not Found\r\n"
                    "Content-Length: " + std::to_string(json_errcd.size()) + "\r\n"
                    "Content-Type: application/json\r\n"  
                    "\r\n"  
                    + json_errcd;
                boost::asio::write(socket, boost::asio::buffer(httpErrorResponse));
                socket.close();
                continue;
            } 
            

            //下发表项操作，需要确定下发方案后再编写
            //
            char* c_scid = (char*)scid.c_str();
            char* c_dcid = (char*)dcid.c_str();
            std::string srid = result1["rid"].asString();
            char* c_srid = (char*)srid.c_str();
            std::string drid = result2["rid"].asString();
            char* c_drid = (char*)drid.c_str();
            std::string smac = result1["mac"].asString();
            char* c_smac = (char*)smac.c_str();
            std::string dmac = result2["mac"].asString();
            char* c_dmac = (char*)dmac.c_str();
            std::string sifn = result1["ifn"].asString();
            char* c_sifn = (char*)sifn.c_str();
            std::string difn = result2["ifn"].asString();
            char* c_difn = (char*)difn.c_str();
            std::string sserviceid = result1["service_id"].asString();
            int scheck = 0, scache = 0;
            std::string dserviceid = result2["service_id"].asString();
            int dcheck = 0, dcache = 0;

            //服务标识对应标志位判断
            scheck = Functions::getCheck(sserviceid);
            scache = Functions::getCache(sserviceid);
            dcheck = Functions::getCheck(dserviceid);
            dcache = Functions::getCache(dserviceid);
            
            if(scid != "" && srid != "" && smac != "" && sifn != "" && dcid != "" && drid != "" && dmac != "" && difn != ""){
                //test
                std::cout <<  "recept预下发内容:" << std::endl
                << c_scid << std::endl
                << c_srid << std::endl
                << c_smac << std::endl
                << c_sifn << std::endl
                << scache << scheck << std::endl
                << c_dcid << std::endl
                << c_drid << std::endl
                << c_dmac << std::endl
                << c_difn << std::endl
                << "0" << dcache << dcheck << std::endl;
		        sln_add_cid(0, c_scid, c_srid, scache, scheck, c_smac, c_sifn);
                sln_add_cid(0, c_dcid, c_drid, dcache, dcheck, c_dmac, c_difn);
                // sln_add_cid(0, c_scid, c_srid, c_smac, c_sifn);
                // sln_add_cid(0, c_dcid, c_drid, c_dmac, c_difn);

                //redis下发
                Json::Value src_;
                src_["rid"] = srid;
                src_["mac"] = smac;
                src_["ifn"] = sifn;
                src_["pktid"] = 0;
                src_["multicast"] = 0;
                src_["cache"] = scache;
                src_["check"] = scheck;
                Json::Value dst_;
                dst_["rid"] = drid;
                dst_["mac"] = dmac;
                dst_["ifn"] = difn;
                dst_["pktid"] = 0;
                dst_["multicast"] = 0;
                dst_["cache"] = dcache;
                dst_["check"] = dcheck;
                // std::string src_str = src_.toStyledString();
                // std::string dst_str = dst_.toStyledString();
                Json::StreamWriterBuilder writer;
                writer["indentation"] = "";
                std::string src_str = Json::writeString(writer, src_);
                std::string dst_str = Json::writeString(writer, dst_);
                RedisCli::HSET_val("SLN_CID_TABLE", scid, src_str);
                RedisCli::HSET_val("SLN_CID_TABLE", dcid, dst_str);
            }

            //向服务器发送接线请求
            std::string jsonData_str = jsonData.toStyledString();
            Json::Value res = Functions::send_post_request(SERVER_IP + "/connect", jsonData_str);
            //判断服务器接线是否成功,直接返回errno
            err_code["err_no"] = res["err_no"];
            std::string json_errcd = "{\"err_no\":\"" + res["err_no"].asString() + "\"}";
            
            std::string httpErrorResponse = "HTTP/1.1 200 OK\r\n"
                "Content-Length: " + std::to_string(json_errcd.size()) + "\r\n"
                "Content-Type: application/json\r\n"  
                "\r\n"  
                + json_errcd;
            boost::asio::write(socket, boost::asio::buffer(httpErrorResponse));

        }else{
            
            err_code["err_no"] = 400;
            std::string json_errcd = "{\"err_no\":\"400\"}";
            
            std::string httpErrorResponse = "HTTP/1.1 400 Bad Request\r\n"
                "Content-Length: " + std::to_string(json_errcd.size()) + "\r\n"
                "Content-Type: application/json\r\n"  
                "\r\n"  
                + json_errcd;
            boost::asio::write(socket, boost::asio::buffer(httpErrorResponse));
        }


        socket.close();
    }
}
//******************************************************************************************************************************************************************************
void Server::Recept()
{
    io_context io_context;
    tcp::endpoint endpoint(tcp::v4(), 40002);
    tcp::acceptor acceptor(io_context, endpoint);
    Json::Value err_code;


    
    while (true) {
        tcp::socket socket(io_context);
        acceptor.accept(socket);

        //测试用
        std::cout << "Recept:收到服务器通知" << std::endl;

        boost::system::error_code error;

        // 读取请求数据
        boost::asio::streambuf buffer;
        boost::asio::streambuf::mutable_buffers_type bufs = buffer.prepare(1024);
        size_t n = socket.read_some(bufs);
        buffer.commit(n);
        


        if (!error) {
                //  解析请求 把请求存在字符串request中
            boost::asio::streambuf::const_buffers_type data = buffer.data();
            std::string request(boost::asio::buffer_cast<const char*>(data), boost::asio::buffer_size(data));
            // std::string request;
            //std::istream request_stream(&buffer);
            // while (!request_stream.eof()) {
            //     std::string line;
            //     std::getline(request_stream, line);
            //     request += line + "\n";
            // }

            // 解析请求中的JSON数据
            //std::cout << request << std::endl;
            size_t jsonStart = request.find("["); // 查找JSON数组的开始
            size_t jsonEnd  = request.rfind("]"); // 查找JSON数组的结束
            //std::cout << jsonStart << std::endl << jsonEnd << std::endl;
            
            if (jsonStart == std::string::npos || jsonEnd == std::string::npos || jsonStart > request.size() || jsonEnd > request.size())  {
                err_code["err_no"] = 400;
                std::string json_errcd = err_code.toStyledString();
                std::string httpErrorResponse = "HTTP/1.1 400 Bad Request\r\n"
                    "Content-Length: " + std::to_string(json_errcd.size()) + "\r\n"
                    "Content-Type: application/json\r\n"  
                    "\r\n"  
                    + json_errcd;
                boost::asio::write(socket, boost::asio::buffer(httpErrorResponse));
            }
            std::string ArrString = request.substr(jsonStart, jsonEnd - jsonStart + 1);
            Json::CharReaderBuilder reader;
            Json::Value jsonArr;
            std::istringstream jsonStream(ArrString);
            Json::parseFromStream(reader, jsonStream, &jsonArr, nullptr);
            //std::cout << "jsonArr:" << jsonArr << std::endl;
            if(!jsonArr.isArray()){
                //test
                std::cout << "解析json数组失败" << std::endl;
                continue;
            }
            const Json::Value& srcData = jsonArr[0];
            const Json::Value& dstData = jsonArr[1];

            

            //下发表项操作，需要确定下发方案后再编写
            //
            std::string scid = srcData["cid"].asString();
            char* c_scid = (char*)scid.c_str();
            std::string dcid = dstData["cid"].asString();
            char* c_dcid = (char*)dcid.c_str();
            std::string srid = srcData["route_id"].asString();
            char* c_srid = (char*)srid.c_str();
            std::string drid = dstData["route_id"].asString();
            char* c_drid = (char*)drid.c_str();
            std::string smac = srcData["mac"].asString();
            char* c_smac = (char*)smac.c_str();
            std::string dmac = dstData["mac"].asString();
            char* c_dmac = (char*)dmac.c_str();
            std::string sifn = srcData["ifn"].asString();
            char* c_sifn = (char*)sifn.c_str();
            std::string difn = dstData["ifn"].asString();
            char* c_difn = (char*)difn.c_str();
            std::string sserviceid = srcData["service_id"].asString();
            int scheck = 0, scache = 0;
            std::string dserviceid = dstData["service_id"].asString();
            int dcheck = 0, dcache = 0;

            //服务标识对应标志位判断
            scheck = Functions::getCheck(sserviceid);
            scache = Functions::getCache(sserviceid);
            dcheck = Functions::getCheck(dserviceid);
            dcache = Functions::getCache(dserviceid);


            if(scid != "" && srid != "" && smac != "" && sifn != "" && dcid != "" && drid != "" && dmac != "" && difn != ""){
                //test
                std::cout <<  "recept预下发内容:" << std::endl
                << c_scid << std::endl
                << c_srid << std::endl
                << c_smac << std::endl
                << c_sifn << std::endl
                << sserviceid << std::endl
                << scache << scheck << std::endl
                << c_dcid << std::endl
                << c_drid << std::endl
                << c_dmac << std::endl
                << c_difn << std::endl
                << dserviceid << std::endl
                << "0" << dcache << dcheck << std::endl;
		        sln_add_cid(0, c_scid, c_srid, scache, scheck, c_smac, c_sifn);
                sln_add_cid(0, c_dcid, c_drid, dcache, dcheck, c_dmac, c_difn);
                // sln_add_cid(0, c_scid, c_srid, c_smac, c_sifn);
                // sln_add_cid(0, c_dcid, c_drid, c_dmac, c_difn);
                
                
                //redis下发
                Json::Value src_;
                src_["rid"] = srid;
                src_["mac"] = smac;
                src_["ifn"] = sifn;
                src_["pktid"] = 0;
                src_["multicast"] = 0;
                src_["cache"] = scache;
                src_["check"] = scheck;
                Json::Value dst_;
                dst_["rid"] = drid;
                dst_["mac"] = dmac;
                dst_["ifn"] = difn;
                dst_["pktid"] = 0;
                dst_["multicast"] = 0;
                dst_["cache"] = dcache;
                dst_["check"] = dcheck;
                Json::StreamWriterBuilder writer;
                writer["indentation"] = "";
                std::string src_str = Json::writeString(writer, src_);
                std::string dst_str = Json::writeString(writer, dst_);
                // std::string src_str = src_.toStyledString();
                // std::string dst_str = dst_.toStyledString();
                RedisCli::HSET_val("SLN_CID_TABLE", scid, src_str);
                RedisCli::HSET_val("SLN_CID_TABLE", dcid, dst_str);

                err_code["err_no"] = 0;
                std::string json_errcd = err_code.toStyledString();
                std::string httpErrorResponse = "HTTP/1.1 200 OK\r\n"
                    "Content-Length: " + std::to_string(json_errcd.size()) + "\r\n"
                    "Content-Type: application/json\r\n"  
                    "\r\n"  
                    + json_errcd;

                boost::asio::write(socket, boost::asio::buffer(httpErrorResponse));
            }


        }else{
            
            err_code["err_no"] = 400;
            std::string json_errcd = err_code.toStyledString();
            
            std::string httpErrorResponse = "HTTP/1.1 400 Bad Request\r\n"
                "Content-Length: " + std::to_string(json_errcd.size()) + "\r\n"
                "Content-Type: application/json\r\n"  
                "\r\n"  
                + json_errcd;
            boost::asio::write(socket, boost::asio::buffer(httpErrorResponse));
        }


        socket.close();
    }
}
//******************************************************************************************************************************************************************************
void Server::ListenCidBackRid()
{
    int sockfd, newsockfd;      //两个socket号
    socklen_t client_len;
    struct sockaddr_in server_addr, client_addr;    //保存本地地址信息与客户端地址信息
    char buffer[4096] = { 0 };
    Json::Value jsonData;

    sockfd = socket(AF_INET, SOCK_STREAM, 0);       //建立响应socket
    if (sockfd < 0) {
        std::cerr << "Error opening socket." << std::endl;
        exit;
    }

    server_addr.sin_family = AF_INET;               //AF_INET代表ipv4
    server_addr.sin_addr.s_addr = INADDR_ANY;       //获取主机接收的所有响应
    server_addr.sin_port = htons(40123);              //指定端口为40123

    if (bind(sockfd, (struct sockaddr*) & server_addr, sizeof(server_addr)) < 0) {      //绑定本地IP与端口号
        std::cerr << "Error binding socket." << std::endl;
        exit;
    }

    listen(sockfd, 5);                              //设置监听状态

    while (true) {
        client_len = sizeof(client_addr);           //需要的内存大小

        //测试用
        std::cout << "等待连接" << std::endl;

        newsockfd = accept(sockfd, (struct sockaddr*) & client_addr, &client_len);      //等待连接,返回服务器端建立的socket
        if (newsockfd < 0) {
            std::cerr << "Error accepting connection." << std::endl;
            continue;
        }

        // Receive JSON data from client
        //此处ssize_t型改成了int型,在Linux中可以改回来
        int bytes_received = recv(newsockfd, buffer, sizeof(buffer), 0);                //接收数据
        if (bytes_received < 0) {
            std::cerr << "Error receiving data." << std::endl;
            close_socket(newsockfd);
            continue;
        }

        std::string jsonString(buffer, bytes_received);

        //测试用
        std::cout << "listencid:接收到数据" << std::endl;
        std::cout << jsonString << std::endl;

        // Parse JSON data
        std::string jsonBody = Functions::extractJsonData(jsonString);
        Json::CharReaderBuilder reader;
        Json::Value root;
        JSONCPP_STRING errs;
        std::istringstream iss(jsonBody);//把收到的数据转化为istream类型的引用
        bool parsingSuccessful = Json::parseFromStream(reader, iss, &root, &errs);
        if (!parsingSuccessful) {
            std::cerr << "Error parsing JSON data: " << errs << std::endl;
            close_socket(newsockfd);
            continue;
        }

        // Process JSON data
        std::string cid = root["cid"].asString();

        //测试用
        std::cout << "listencid:开始请求返回值" << std::endl;

        Json::Value result = Functions::processCidAndGetRid(cid);//根据不同的请求调用不同的函数
        

        
        Json::StreamWriterBuilder writer;
        std::string resultString = Json::writeString(writer, result);


        std::string httpResponse = "HTTP/1.1 200 OK\r\n"
            "Content-Length: " + std::to_string(resultString.size()) + "\r\n"
            "Content-Type: text/plain\r\n"  // 添加 Content-Type
            "\r\n"  // 头部和响应体之间的空行
            + resultString;



        // Send result back to client       
        //此处ssize_t型改成了int型,在Linux中可以改回来

        //测试用
        std::cout << "listencid:返回数据" << std::endl;

        int bytes_sent = send(newsockfd, httpResponse.c_str(), httpResponse.length(), 0);   //发送数据
        if (bytes_sent < 0) {
            std::cerr << "Error sending data." << std::endl;
        }

        //测试用
        std::cout << "listencid:关闭客户端socket" << std::endl;
        close_socket(newsockfd);
    }

    close_socket(sockfd);
}
//******************************************************************************************************************************************************************************
void Server::ListenRidBackCid()
{
    int sockfd, newsockfd;      //两个socket号
    socklen_t client_len;
    struct sockaddr_in server_addr, client_addr;    //保存本地地址信息与客户端地址信息
    char buffer[4096] = { 0 };
    Json::Value jsonData;

    sockfd = socket(AF_INET, SOCK_STREAM, 0);       //建立响应socket
    if (sockfd < 0) {
        std::cerr << "Error opening socket." << std::endl;
        exit;
    }

    server_addr.sin_family = AF_INET;               //AF_INET代表ipv4
    server_addr.sin_addr.s_addr = INADDR_ANY;       //获取主机接收的所有响应
    server_addr.sin_port = htons(40124);              //指定端口为402

    if (bind(sockfd, (struct sockaddr*) & server_addr, sizeof(server_addr)) < 0) {      //绑定本地IP与端口号
        std::cerr << "Error binding socket." << std::endl;
        exit;
    }

    listen(sockfd, 5);                              //设置监听状态

    while (true) {
        client_len = sizeof(client_addr);           //需要的内存大小
        newsockfd = accept(sockfd, (struct sockaddr*) & client_addr, &client_len);      //等待连接,返回服务器端建立的socket
        if (newsockfd < 0) {
            std::cerr << "Error accepting connection." << std::endl;
            continue;
        }

        // Receive JSON data from client
        //此处ssize_t型改成了int型,在Linux中可以改回来
        int bytes_received = recv(newsockfd, buffer, sizeof(buffer), 0);                //接收数据
        if (bytes_received < 0) {
            std::cerr << "Error receiving data." << std::endl;
            close_socket(newsockfd);
            continue;
        }

        std::string jsonString(buffer, bytes_received);

        // Parse JSON data
        std::string jsonBody = Functions::extractJsonData(jsonString);
        Json::CharReaderBuilder reader;
        Json::Value root;
        JSONCPP_STRING errs;
        std::istringstream iss(jsonBody);//把收到的数据转化为istream类型的引用
        bool parsingSuccessful = Json::parseFromStream(reader, iss, &root, &errs);
        if (!parsingSuccessful) {
            std::cerr << "Error parsing JSON data: " << errs << std::endl;
            close_socket(newsockfd);
            continue;
        }

        // Process JSON data
        std::string rid = root["rid"].asString();
        std::string result = Functions::processRidAndGetCid(rid);//根据不同的请求调用不同的函数
        std::string resultString = "{"                           //组建json格式字符串,返回{"cid":"12345"}
            "\"cid\":\"" + result + "\""
            "}";
        std::string httpResponse = "HTTP/1.1 200 OK\r\n"
            "Content-Length: " + std::to_string(resultString.size()) + "\r\n"
            "Content-Type: text/plain\r\n"  // 添加 Content-Type
            "\r\n"  // 头部和响应体之间的空行
            + resultString;


        // Convert result to JSON string
        //Json::StreamWriterBuilder writer;
        //std::string resultString = Json::writeString(writer, result);

        // Send result back to client       
        //此处ssize_t型改成了int型,在Linux中可以改回来
        int bytes_sent = send(newsockfd, httpResponse.c_str(), httpResponse.length(), 0);   //发送数据
        if (bytes_sent < 0) {
            std::cerr << "Error sending data." << std::endl;
        }

        close_socket(newsockfd);
    }

    close_socket(sockfd);
}
//******************************************************************************************************************************************************************************
void Server::ListenCidBackMid()
{
    int sockfd, newsockfd;      //两个socket号
    socklen_t client_len;
    struct sockaddr_in server_addr, client_addr;    //保存本地地址信息与客户端地址信息
    char buffer[4096] = { 0 };
    Json::Value jsonData;

    sockfd = socket(AF_INET, SOCK_STREAM, 0);       //建立响应socket
    if (sockfd < 0) {
        std::cerr << "Error opening socket." << std::endl;
        exit;
    }

    server_addr.sin_family = AF_INET;               //AF_INET代表ipv4
    server_addr.sin_addr.s_addr = INADDR_ANY;       //获取主机接收的所有响应
    server_addr.sin_port = htons(40125);              //指定端口为403

    if (bind(sockfd, (struct sockaddr*) & server_addr, sizeof(server_addr)) < 0) {      //绑定本地IP与端口号
        std::cerr << "Error binding socket." << std::endl;
        exit;
    }

    listen(sockfd, 5);                              //设置监听状态

    while (true) {
        client_len = sizeof(client_addr);           //需要的内存大小
        newsockfd = accept(sockfd, (struct sockaddr*) & client_addr, &client_len);      //等待连接,返回服务器端建立的socket
        if (newsockfd < 0) {
            std::cerr << "Error accepting connection." << std::endl;
            continue;
        }

        // Receive JSON data from client
        //此处ssize_t型改成了int型,在Linux中可以改回来
        int bytes_received = recv(newsockfd, buffer, sizeof(buffer), 0);                //接收数据
        if (bytes_received < 0) {
            std::cerr << "Error receiving data." << std::endl;
            close_socket(newsockfd);
            continue;
        }

        std::string jsonString(buffer, bytes_received);

        // Parse JSON data
        std::string jsonBody = Functions::extractJsonData(jsonString);
        Json::CharReaderBuilder reader;
        Json::Value root;
        JSONCPP_STRING errs;
        std::istringstream iss(jsonBody);//把收到的数据转化为istream类型的引用
        bool parsingSuccessful = Json::parseFromStream(reader, iss, &root, &errs);
        if (!parsingSuccessful) {
            std::cerr << "Error parsing JSON data: " << errs << std::endl;
            close_socket(newsockfd);
            continue;
        }

        // Process JSON data
        std::string cid = root["cid"].asString();
        std::string result = Functions::processCidAndGetMid(cid);//根据不同的请求调用不同的函数
        std::string resultString = "{"                           //组建json格式字符串,返回{"mid":""}
            "\"mid\":" + result +
            "}";
        std::string httpResponse = "HTTP/1.1 200 OK\r\n"
            "Content-Length: " + std::to_string(resultString.size()) + "\r\n"
            "Content-Type: text/plain\r\n"  // 添加 Content-Type
            "\r\n"  // 头部和响应体之间的空行
            + resultString;

        // Convert result to JSON string
        //Json::StreamWriterBuilder writer;
        //std::string resultString = Json::writeString(writer, result);

        // Send result back to client       
        //此处ssize_t型改成了int型,在Linux中可以改回来
        int bytes_sent = send(newsockfd, httpResponse.c_str(), httpResponse.length(), 0);   //发送数据
        if (bytes_sent < 0) {
            std::cerr << "Error sending data." << std::endl;
        }

        close_socket(newsockfd);
    }

    close_socket(sockfd);
}
//******************************************************************************************************************************************************************************
void Server::ListenRidBackMid()
{
    int sockfd, newsockfd;      //两个socket号
    socklen_t client_len;
    struct sockaddr_in server_addr, client_addr;    //保存本地地址信息与客户端地址信息
    char buffer[4096] = { 0 };
    Json::Value jsonData;

    sockfd = socket(AF_INET, SOCK_STREAM, 0);       //建立响应socket
    if (sockfd < 0) {
        std::cerr << "Error opening socket." << std::endl;
        exit;
    }

    server_addr.sin_family = AF_INET;               //AF_INET代表ipv4
    server_addr.sin_addr.s_addr = INADDR_ANY;       //获取主机接收的所有响应
    server_addr.sin_port = htons(40126);              //指定端口为404

    if (bind(sockfd, (struct sockaddr*) & server_addr, sizeof(server_addr)) < 0) {      //绑定本地IP与端口号
        std::cerr << "Error binding socket." << std::endl;
        exit;
    }

    listen(sockfd, 5);                              //设置监听状态

    while (true) {
        client_len = sizeof(client_addr);           //需要的内存大小
        newsockfd = accept(sockfd, (struct sockaddr*) & client_addr, &client_len);      //等待连接,返回服务器端建立的socket
        if (newsockfd < 0) {
            std::cerr << "Error accepting connection." << std::endl;
            continue;
        }

        // Receive JSON data from client
        //此处ssize_t型改成了int型,在Linux中可以改回来
        int bytes_received = recv(newsockfd, buffer, sizeof(buffer), 0);                //接收数据
        if (bytes_received < 0) {
            std::cerr << "Error receiving data." << std::endl;
            close_socket(newsockfd);
            continue;
        }

        std::string jsonString(buffer, bytes_received);

        // Parse JSON data
        std::string jsonBody = Functions::extractJsonData(jsonString);
        Json::CharReaderBuilder reader;
        Json::Value root;
        JSONCPP_STRING errs;
        std::istringstream iss(jsonBody);//把收到的数据转化为istream类型的引用
        bool parsingSuccessful = Json::parseFromStream(reader, iss, &root, &errs);
        if (!parsingSuccessful) {
            std::cerr << "Error parsing JSON data: " << errs << std::endl;
            close_socket(newsockfd);
            continue;
        }

        // Process JSON data
        std::string rid = root["rid"].asString();
        std::string result = Functions::processRidAndGetMid(rid);//根据不同的请求调用不同的函数
        std::string resultString = "{"                           //组建json格式字符串,返回{"mid":""}
            "\"mid\":" + result +
            "}";
        std::string httpResponse = "HTTP/1.1 200 OK\r\n"
            "Content-Length: " + std::to_string(resultString.size()) + "\r\n"
            "Content-Type: text/plain\r\n"  // 添加 Content-Type
            "\r\n"  // 头部和响应体之间的空行
            + resultString;


        // Convert result to JSON string
        //Json::StreamWriterBuilder writer;
        //std::string resultString = Json::writeString(writer, result);

        // Send result back to client       
        //此处ssize_t型改成了int型,在Linux中可以改回来
        int bytes_sent = send(newsockfd, httpResponse.c_str(), httpResponse.length(), 0);   //发送数据
        if (bytes_sent < 0) {
            std::cerr << "Error sending data." << std::endl;
        }

        close_socket(newsockfd);
    }

    close_socket(sockfd);
}
